package com.dd.stack.se.stream.io.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/8/21 12:00
 * @Description 类功能作用说明
 */
public class TCPServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            // 创建服务器套接字，绑定到8888端口
            serverSocket = new ServerSocket(8888);
            System.out.println("服务器已启动，等待客户端连接...");

            // 监听客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接: " + clientSocket.getInetAddress());

            // 获取输入输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String inputLine;
            // 读取客户端发送的消息
            while ((inputLine = in.readLine()) != null) {
                System.out.println("客户端: " + inputLine);

                // 回复客户端
                out.println("服务器已收到: " + inputLine);

                // 如果客户端发送"bye"，则关闭连接
                if (inputLine.equals("bye")) {
                    break;
                }
            }

            // 关闭资源
            in.close();
            out.close();
            clientSocket.close();
        } catch (IOException e) {
            System.out.println("服务器异常: " + e.getMessage());
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
